<!-- 用户编辑弹窗 -->
<template>
  <ele-modal
    :width="680"
    :visible="visible"
    :confirm-loading="loading"
    :title="isUpdate ? '修改企业' : '新建企业'"
    :body-style="{ paddingBottom: '8px' }"
    @update:visible="updateVisible"
    @ok="save"
  >
    <a-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-col="styleResponsive ? { md: 3, sm: 4, xs: 24 } : { flex: '80px' }"
      :wrapper-col="
        styleResponsive ? { md: 21, sm: 20, xs: 24 } : { flex: '1' }
      "
    >
      <a-row>
        <a-col :span="24">
          <a-form-item label="企业名称" name="name">
            <a-input
              allow-clear
              placeholder="请输入企业名称"
              v-model:value="form.name"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span="24">
          <a-form-item label="企业地址" name="address">
            <a-input
              allow-clear
              placeholder="请输入企业地址"
              v-model:value="form.address"
            />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutttr="24">
        <a-col
          v-bind="styleResponsive ? { md: 12, sm: 24, xs: 24 } : { span: 12 }"
        >
          <a-form-item :label-col="{ span: 6 }" label="联系人" name="hr">
            <a-input
              allow-clear
              placeholder="请输入企业联系人"
              v-model:value="form.hr"
            />
          </a-form-item>
          <a-form-item :label-col="{ span: 6 }" label="联系电话" name="phone">
            <a-input
              allow-clear
              placeholder="请输入联系电话"
              v-model:value="form.phone"
            />
          </a-form-item>
          <a-form-item :label-col="{ span: 6 }" label="联系邮箱" name="email">
            <a-input
              allow-clear
              placeholder="请输入联系邮箱"
              v-model:value="form.email"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item :label-col="{ span: 8 }" label="企业logo" name="logo">
            <ele-image-upload
              v-model:value="images"
              :limit="1"
              :before-upload="onBeforeUpload"
              :remove-handler="removeHandler"
              :item-style="{ width: '152px', height: '90px' }"
              :button-style="{ width: '152px', height: '90px' }"
              @upload="onUpload"
            />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutttr="24">
        <a-col :span="12">
          <a-form-item
            :label-col="{ span: 6 }"
            label="企业位置"
            name="location"
          >
            <a-input
              allow-clear
              placeholder="请输入地图"
              v-model:value="result.lngAndLat"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-button @click="showMap">选择地址</a-button>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24">
          <a-form-item
            label="文章内容"
            :label-col="
              styleResponsive ? { md: 3, sm: 4, xs: 24 } : { flex: '90px' }
            "
            :wrapper-col="
              styleResponsive ? { md: 21, sm: 20, xs: 24 } : { flex: '1' }
            "
          >
            <tinymce-editor v-model:value="form.comment" :init="config" />
          </a-form-item>
        </a-col>
      </a-row>
      <ele-map-picker
        :need-city="true"
        :dark-mode="darkMode"
        v-model:visible="mapVisible"
        @done="onChoose"
      />
    </a-form>
  </ele-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, watch } from 'vue';
  import { message } from 'ant-design-vue/es';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { emailReg, phoneReg } from 'ele-admin-pro/es';
  import { storeToRefs } from 'pinia';
  import { useThemeStore } from '@/store/modules/theme';
  import useFormData from '@/utils/use-form-data';
  import TinymceEditor from '@/components/TinymceEditor/index.vue';
  import type { CenterPoint } from 'ele-admin-pro/es/ele-map-picker/types';
  import { Company } from '@/api/employ/company/model';
  import request from '@/utils/request';
  import {
    addCompany,
    checkExistence,
    updateCompany
  } from '@/api/employ/company';
  import type {
    BeforeUploadType,
    ItemType
  } from 'ele-admin-pro/es/ele-image-upload/types';

  // 是否开启响应式布局
  const themeStore = useThemeStore();
  const { styleResponsive } = storeToRefs(themeStore);

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  const props = defineProps<{
    // 弹窗是否打开
    visible: boolean;
    // 修改回显的数据
    data?: Company | null;
  }>();
  const mapVisible = ref(false);
  const { darkMode } = storeToRefs(themeStore);
  //
  const formRef = ref<FormInstance | null>(null);

  // 是否是修改
  const isUpdate = ref(false);

  // 提交状态
  const loading = ref(false);
  // 选择结果
  const result = reactive({
    location: '',
    address: '',
    lngAndLat: ''
  });
  const images = ref<any>([]);
  const img_obj = reactive<any>({
    url: ''
  });
  // 表单数据
  const { form, resetFields, assignFields } = useFormData<Company>({
    companyId: undefined,
    name: '',
    address: '',
    hr: '',
    email: '',
    phone: '',
    location: '',
    comment: ''
  });

  // 表单验证规则
  const rules = reactive<Record<string, Rule[]>>({
    name: [
      {
        required: true,
        type: 'string',
        validator: (_rule: Rule, value: string) => {
          return new Promise<void>((resolve, reject) => {
            if (!value) {
              return reject('请输入企业名称');
            }
            checkExistence('name', value, props.data?.companyId)
              .then(() => {
                reject('该企业已经存在');
              })
              .catch(() => {
                resolve();
              });
          });
        },
        trigger: 'blur'
      }
    ],
    email: [
      {
        pattern: emailReg,
        message: '邮箱格式不正确',
        type: 'string',
        trigger: 'blur'
      }
    ],
    phone: [
      {
        pattern: phoneReg,
        message: '手机号格式不正确',
        type: 'string',
        trigger: 'blur'
      }
    ]
  });
  const showMap = () => {
    mapVisible.value = true;
  };
  const onUpload = (d: ItemType) => {
    const item = images.value.find((t: any) => t.uid === d.uid) ?? d;
    // item 包含的字段参考前面说明
    item.status = 'uploading';
    const formData = new FormData();
    formData.append('file', item.file);
    request({
      url: '/file/upload',
      method: 'post',
      data: formData,
      onUploadProgress: (e: any) => {
        // 文件上传进度回调
        if (e.lengthComputable) {
          item.progress = (e.loaded / e.total) * 100;
        }
      }
    })
      .then((res) => {
        if (res.data.code === 0) {
          item.status = 'done';
          item.url = res.data.data;
          form.logo = res.data.data;
        }
      })
      .catch((e: Error) => {
        message.warning(e.message);
        item.status = 'exception';
      });
  };
  const onBeforeUpload: BeforeUploadType = (file: File) => {
    // file 即选择后的文件
    if (!file.type.startsWith('image')) {
      message.error('只能选择图片');
      return false;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('大小不能超过 2MB');
      return false;
    }
  };
  const removeHandler = (item) => {
    images.value.forEach((d: any) => {
      if (d.uid === item.uid) {
        images.value = [];
        form.logo = '';
        d.deleted = 1;
      }
    });
  };
  //编辑器配置
  const config = ref({
    height: 300,
    external_plugins: {
      editor135: 'http://cdn.cqtlcm.com/plugin/plugin.js'
    },
    menubar: false,
    toolbar:
      'removeformat forecolor backcolor bold italic underline strikethrough | alignleft aligncenter alignright alignjustify outdent indent | formatselect fontselect editor135',
    plugins:
      'editor135 media image link table code preview fullscreen wordcount',
    automatic_uploads: true,
    paste_data_images: true, // 设置为允许粘帖图片
    images_upload_handler: (blobInfo, success, error) => {
      const file = blobInfo.blob();
      // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
      const formData = new FormData();
      formData.append('file', file, file.name);
      request({
        url: '/file/upload',
        method: 'post',
        data: formData
      })
        .then((res) => {
          if (res.data.data) {
            success(res.data.data);
          } else {
            error(res.data.message);
          }
        })
        .catch((e) => {
          error(e.message);
        });
    },
    file_picker_callback: (callback, value, meta) => {
      const input = document.createElement('input');
      input.setAttribute('type', 'file');
      // 设定文件可选类型
      if (meta.filetype === 'image') {
        input.setAttribute('accept', 'image/*');
      } else if (meta.filetype === 'media') {
        input.setAttribute('accept', 'video/*');
        //input.setAttribute('accept', 'audio/*');
      }
      input.onchange = () => {
        const file = input.files[0];
        // 使用 axios 上传，实际开发这段建议写在 api 中再调用 api
        const formData = new FormData();
        formData.append('file', file, file.name);
        request({
          url: '/file/upload',
          method: 'post',
          data: formData
        })
          .then((res) => {
            if (res.data.data) {
              callback(res.data.data);
            } else {
              message.error(res.data.message);
            }
          })
          .catch((e) => {
            message.error(e.message);
          });
      };
      input.click();
    }
  });
  /* 地图选择后回调 */
  const onChoose = (location: CenterPoint) => {
    result.location = `${location.city?.province}/${location.city?.city}/${location.city?.district}`;
    result.address = `${location.name} ${location.address}`;
    result.lngAndLat = `${location.lng},${location.lat}`;
    mapVisible.value = false;
  };
  /* 保存编辑 */
  const save = () => {
    if (!formRef.value) {
      return;
    }
    formRef.value
      .validate()
      .then(() => {
        loading.value = true;
        const saveOrUpdate = isUpdate.value ? updateCompany : addCompany;
        form.location = result.lngAndLat;
        saveOrUpdate(form)
          .then((msg) => {
            loading.value = false;
            message.success(msg);
            updateVisible(false);
            emit('done');
          })
          .catch((e) => {
            loading.value = false;
            message.error(e.message);
          });
      })
      .catch(() => {});
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  watch(
    () => props.visible,
    (visible) => {
      if (visible) {
        if (props.data) {
          assignFields(props.data);
          if (props.data.location) {
            result.lngAndLat = props.data.location;
          }
          if (props.data.logo != null && props.data.logo != '') {
            img_obj.url = props.data.logo;
            images.value.push(img_obj);
          }
          isUpdate.value = true;
        } else {
          isUpdate.value = false;
        }
      } else {
        resetFields();
        images.value = [];
        result.lngAndLat = '';
        formRef.value?.clearValidate();
      }
    }
  );
</script>
